package com.property.demo.service.impl;

import com.property.demo.model.Community;
import com.property.demo.repository.CommunityRepository;
import com.property.demo.repository.BuildingRepository;
import com.property.demo.service.CommunityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommunityServiceImpl implements CommunityService {

    @Autowired
    private CommunityRepository communityRepository;
    
    @Autowired
    private BuildingRepository buildingRepository;
    
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<Community> findAll() {
        return communityRepository.findAll();
    }

    @Override
    public Page<Community> findAll(Pageable pageable) {
        return communityRepository.findAll(pageable);
    }

    @Override
    public Page<Community> findByFilters(String name, Pageable pageable) {
        Specification<Community> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            
            if (name != null && !name.isEmpty()) {
                predicates.add(criteriaBuilder.like(criteriaBuilder.lower(root.get("name")), "%" + name.toLowerCase() + "%"));
            }
            
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
        
        return communityRepository.findAll(spec, pageable);
    }

    @Override
    public Community findById(Long id) {
        return communityRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("Community not found with id: " + id));
    }

    @Override
    public Community save(Community community) {
        return communityRepository.save(community);
    }

    @Override
    public Community update(Long id, Community communityDetails) {
        Community community = findById(id);
        
        community.setName(communityDetails.getName());
        community.setAddress(communityDetails.getAddress());
        community.setArea(communityDetails.getArea());
        community.setTotalBuildings(communityDetails.getTotalBuildings());
        community.setTotalHomes(communityDetails.getTotalHomes());
        community.setDeveloperName(communityDetails.getDeveloperName());
        community.setPropertyCompany(communityDetails.getPropertyCompany());
        
        return communityRepository.save(community);
    }

    @Override
    public void delete(Long id) {
        Community community = findById(id);
        communityRepository.delete(community);
    }

    @Override
    public List<Community> findByNameContaining(String name) {
        return communityRepository.findByNameContaining(name);
    }
    
    @Override
    public Map<String, Object> getStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 获取小区总数
        long totalCommunities = communityRepository.count();
        statistics.put("totalCommunities", totalCommunities);
        
        // 获取总栋数
        Query buildingsQuery = entityManager.createQuery(
            "SELECT SUM(c.totalBuildings) FROM Community c");
        Number totalBuildings = (Number) buildingsQuery.getSingleResult();
        statistics.put("totalBuildings", totalBuildings != null ? totalBuildings.intValue() : 0);
        
        // 获取总户数
        Query homesQuery = entityManager.createQuery(
            "SELECT SUM(c.totalHomes) FROM Community c");
        Number totalHomes = (Number) homesQuery.getSingleResult();
        statistics.put("totalHomes", totalHomes != null ? totalHomes.intValue() : 0);
        
        // 获取本月新增小区数
        Query recentQuery = entityManager.createQuery(
            "SELECT COUNT(c) FROM Community c WHERE YEAR(c.createdAt) = YEAR(CURRENT_DATE) AND MONTH(c.createdAt) = MONTH(CURRENT_DATE)");
        Number recentAdded = (Number) recentQuery.getSingleResult();
        statistics.put("recentAdded", recentAdded != null ? recentAdded.intValue() : 0);
        
        return statistics;
    }
} 